/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <devmon/driver_abi.h>
#include <dlfcn.h>
#include <gtest/gtest.h>
#include <mc/log.h>
#include <memory>
#include <test_utilities/test_base.h>
#include <unordered_map>

#include "../../../../drivers/debounce/average/average.h"
#include "../../test_utils/root_object.h"

using namespace dev;
using namespace devmon;

namespace drivers {
namespace average {
namespace test {

class average_test_service : public mc::engine::service {
public:
    average_test_service(const std::string& name) : mc::engine::service(name) {
    }
};

class AverageAbiTest : public mc::test::TestWithEngine {
public:
    static void SetUpTestSuite() {
        TestWithEngine::SetUpTestSuite();
        m_test_service = mc::make_shared<average_test_service>("bmc.kepler.test_average_abi");
        m_test_service->init();
        m_test_service->start();

        // 创建根对象
        m_root_object = root_object::create_root_object(m_test_service.get());

        load_driver();
    }

    static void TearDownTestSuite() {
        m_test_service->stop();
        m_root_object.reset();

        if (m_driver_handle != nullptr) {
            dlclose(m_driver_handle);
            m_driver_handle = nullptr;
        }

        m_test_service.reset();
        TestWithEngine::TearDownTestSuite();
    }

    void SetUp() override {
        // 测试用例之间无需特殊设置
    }

    void TearDown() override {
        // 测试用例之间无需特殊清理
    }

    static void load_driver() {
        m_driver_handle = dlopen("./opt/bmc/drivers/libAverage.so", RTLD_LAZY);
        if (m_driver_handle == nullptr) {
            MC_THROW(mc::system_exception, "Failed to load Average driver: ${error}",
                     ("error", dlerror()));
        }

        register_device_driver_func func = reinterpret_cast<register_device_driver_func>(
            dlsym(m_driver_handle, "register_device_driver"));
        MC_ASSERT_THROW(func, mc::bad_function_call_exception,
                        "Failed to get register_device_driver function: ${error}",
                        ("error", dlerror()));

        device_driver_t* devices       = nullptr;
        uint8_t          devices_count = 0;
        status_t         ret           = func(&devices, &devices_count);
        MC_ASSERT_THROW(ret == STATUS_OK, mc::bad_function_call_exception,
                        "Failed to get device driver manager: ${error}", ("error", ret));

        m_devices.clear();
        m_devices.reserve(devices_count);
        for (uint8_t i = 0; i < devices_count; i++) {
            auto device_driver = std::make_shared<device_driver_t>(devices[i]);
            m_devices.emplace(device_driver->device_name, device_driver);
        }
    }

    mc::mutable_dict create_test_csr_object(uint32_t size, bool is_signed) {
        return mc::mutable_dict{{"WindowSize", size}, {"IsSigned", is_signed}};
    }

    static mc::shared_ptr<average_test_service>                              m_test_service;
    static std::unordered_map<std::string, std::shared_ptr<device_driver_t>> m_devices;
    static void*                                                             m_driver_handle;
    static root_object_ptr                                                   m_root_object;
};

mc::shared_ptr<average_test_service>                              AverageAbiTest::m_test_service;
std::unordered_map<std::string, std::shared_ptr<device_driver_t>> AverageAbiTest::m_devices;
void*           AverageAbiTest::m_driver_handle = nullptr;
root_object_ptr AverageAbiTest::m_root_object;

// ========================= 驱动注册功能测试 =========================

TEST_F(AverageAbiTest, register_device_driver_success) {
    EXPECT_EQ(m_devices.size(), 1);
    EXPECT_TRUE(m_devices.find("Average") != m_devices.end());
}

TEST_F(AverageAbiTest, device_driver_structure_validation) {
    for (const auto& [device_name, device_driver] : m_devices) {
        EXPECT_FALSE(std::string(device_driver->device_name).empty());
        EXPECT_TRUE(device_driver->ctor != nullptr);
        EXPECT_TRUE(device_driver->init != nullptr);
        EXPECT_TRUE(device_driver->start != nullptr);
        EXPECT_TRUE(device_driver->stop != nullptr);
    }
}

// ========================= Average设备创建测试 =========================

TEST_F(AverageAbiTest, create_average_success) {
    auto device_driver = m_devices["Average"];
    ASSERT_TRUE(device_driver != nullptr);

    auto device = device_driver->ctor(m_test_service.get(), "test_average");
    ASSERT_TRUE(device != nullptr);

    Average* average_device = static_cast<Average*>(device);
    EXPECT_TRUE(average_device != nullptr);
}

TEST_F(AverageAbiTest, create_average_null_service) {
    auto device_driver = m_devices["Average"];
    ASSERT_TRUE(device_driver != nullptr);

    // 传入空服务指针应该返回nullptr
    auto device = device_driver->ctor(nullptr, "test_average");
    EXPECT_EQ(device, nullptr);
}

TEST_F(AverageAbiTest, create_average_null_name) {
    auto device_driver = m_devices["Average"];
    ASSERT_TRUE(device_driver != nullptr);

    // 传入空名称应该返回nullptr
    auto device = device_driver->ctor(m_test_service.get(), nullptr);
    EXPECT_EQ(device, nullptr);
}

// ========================= Average设备初始化测试 =========================

TEST_F(AverageAbiTest, init_average_success) {
    auto device_driver = m_devices["Average"];
    ASSERT_TRUE(device_driver != nullptr);

    auto device = device_driver->ctor(m_test_service.get(), "test_average_init");
    ASSERT_TRUE(device != nullptr);

    auto csr_object = create_test_csr_object(5, false);
    status_t ret = device_driver->init(device, &csr_object, nullptr);
    EXPECT_EQ(ret, STATUS_OK);
}

TEST_F(AverageAbiTest, init_average_null_device) {
    auto device_driver = m_devices["Average"];
    ASSERT_TRUE(device_driver != nullptr);

    auto csr_object = create_test_csr_object(5, false);
    status_t ret = device_driver->init(nullptr, &csr_object, nullptr);
    EXPECT_EQ(ret, STATUS_ERROR);
}

TEST_F(AverageAbiTest, init_average_null_csr_object) {
    auto device_driver = m_devices["Average"];
    ASSERT_TRUE(device_driver != nullptr);

    auto device = device_driver->ctor(m_test_service.get(), "test_average_init_null_csr");
    ASSERT_TRUE(device != nullptr);

    status_t ret = device_driver->init(device, nullptr, nullptr);
    EXPECT_EQ(ret, STATUS_ERROR);
}

} // namespace test
} // namespace average
} // namespace drivers